"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-resource-manager

A test unit used to read user resource files on specified partition of MicroPython firmware
"""
import os
import esp32
import errno
import math
from config import Config
from libs.fontlib import FontLib


RESOURCE_PARTITION = '/res'

try:
	_ = os.stat('fonts')
	RESOURCE_PARTITION = ''
except:
	pass

def mount_resource_partition() -> bool:
	if RESOURCE_PARTITION == '':
		return True

	try:
		os.umount(RESOURCE_PARTITION)
	except OSError as ose:
		if ose.errno == errno.EINVAL:
			pass
		else:
			print(ose)

	res = esp32.Partition.find(esp32.Partition.TYPE_DATA, label=Config.Partition.LABEL)

	if res:
		os.mount(res[0], RESOURCE_PARTITION)
		return True
	else:
		return False

def is_resource_file_exists(filename:str) -> bool:
	try:
		os.stat(f'{RESOURCE_PARTITION}/{filename}')
		return True
	except OSError as ose:
		if str(ose) == '[Errno 2] ENOENT':
			return False
		else:
			raise OSError(ose)

def bitmap_preview(filename):
	with open(filename, 'rb') as bitmap:
		_ = bitmap.readline()
		size = bitmap.readline().replace(b'\n', b'').split(b' ')

		width = int(size[0])
		height = int(size[1])
		bytes_per_row = int(width / 8) + 1

		buffer = bitmap.read()

		for row in range(height):
			for index in range(bytes_per_row):
				data = buffer[row * bytes_per_row + index]
				offset = 8 if (index + 1) * 8 < width else 8 - ((index + 1) * 8 - width)

				print('{:08b}'.format(data)[:offset].replace('0', '.').replace('1', '@'), end='')
			print('')

def chars_preview(fontlib:FontLib, buffer_list:list):
	data_size = fontlib.data_size
	font_height = fontlib.font_height
	bytes_per_row = int(font_height / 8)
	chars_per_row = 120 // font_height

	for char in range(math.ceil(len(buffer_list) / chars_per_row)):
		for count in range(bytes_per_row):
			for col in range(8):
				if count * 8 + col >= font_height: continue
				for buffer in buffer_list[char * chars_per_row:char * chars_per_row + chars_per_row]:
					if len(buffer) < data_size: buffer = bytes(data_size)

					for index in range(count * font_height, count * font_height + font_height):
						data = ''.join(reversed('{:08b}'.format(buffer[index])))
						print('{}'.format(data[col].replace('0', '.').replace('1', '@')), end='')
					print(' ', end='')
				print('')
		print('')


if __name__ == '__main__':
	if mount_resource_partition():
		image_file = 'images/mua.pbm'
		text_file  = 'chushibiao.txt'
		font_file  = 'fonts/chushibiao.bin'

		_ = input('Press enter to preview bitmap...')

		if is_resource_file_exists(image_file):
			bitmap_preview(f'{RESOURCE_PARTITION}/{image_file}')

		if is_resource_file_exists(text_file):
			_ = input('\nPress enter to preview text...')

			chushibiao = None
			with open(f'{RESOURCE_PARTITION}/{text_file}') as file:
				chushibiao = file.read()

			print(chushibiao)

			if is_resource_file_exists(font_file):
				_ = input('\nPress enter to preview fontlib...')

				fontlib = FontLib(f'{RESOURCE_PARTITION}/{font_file}')
				fontlib.info()

				_ = input('\nPress enter to preview chars data...')

				chushibiao = chushibiao.replace('\r', '').replace('\n', '')

				buffer_dict = fontlib.get_characters(chushibiao[:20])
				for unicode, buffer in buffer_dict.items():
					print("{}: {}\n".format(chr(unicode), bytes(buffer)), end='')

				buffer_list = []
				for char in chushibiao[:20]:
					buffer_list.append(buffer_dict[ord(char)])

				_ = input('\nPress enter to preview chars...')

				del chushibiao
				del buffer_dict

				chars_preview(fontlib, buffer_list)

				del buffer_list
				del fontlib

				print('\nTesting done.')
	else:
		print('Failed, cannot mount resource partition.')
